﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using SnippetDoc.Entities;

namespace SnippetDoc.Utils
{
    public class FolderScanner
    {
        public IEnumerable<SnippetFolder> ScanSnippetDirectory(string directoryPath)
        {
            List<SnippetFolder> result = new List<SnippetFolder>();

            if (Directory.Exists(directoryPath) == false)
                throw new FileNotFoundException("The directory " + directoryPath + " does not exist!");

            SnippetFactory factory = new SnippetFactory();

            SnippetFolder folder = new SnippetFolder(ResolveDirectoryName(directoryPath));
            IEnumerable<string> files = Directory.EnumerateFiles(directoryPath, "*.snippet");
            foreach (var fileName in files)
            {
                FileInfo fi = new FileInfo(fileName);
                DateTime lastModified = fi.LastWriteTime;
                IEnumerable<Snippet> snippets = factory.CreateSnippet(XDocument.Load(fileName));

                foreach (var snippet in snippets)
                {
                    snippet.LastModified = lastModified;
                    snippet.FilePath = fileName;
                }

                folder.Snippets.AddRange(snippets);
            }

            IEnumerable<string> subdirectories = Directory.EnumerateDirectories(directoryPath);
            foreach (var directory in subdirectories)
            {
                IEnumerable<SnippetFolder> folders = ScanSnippetDirectory(directory);
                if (folders.Count() > 0)
                {
                    result.AddRange(folders);
                }
            }

            if (files.Count() > 0)
            {
                result.Add(folder);
            }

            return result;
        }

        private string ResolveDirectoryName(string directoryPath)
        {
            return new FileInfo(directoryPath).Name;
        }
    }
}
